<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css ">

    <link href="../css/mui.min.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="../css/header.css" />
    <link rel="stylesheet" type="text/css" href="../css/chat.css" />
    <style>
        html,
        body {
            height: 100%;
            margin: 0px;
            padding: 0px;
            overflow: hidden;
            -webkit-touch-callout: none;
            -webkit-user-select: none;
        }
        
        p>img {
            height: 100%;
            width: 100%;
        }
    </style>
</head>

<body contextmenu="return false;">

    <header class="mui-bar mui-bar-nav title" style="position: fixed;">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left title-color"></a>
        <h1 class="mui-title title-color"><b id="chatting-nickname">" 微 涵 " 聊 天</b></h1>
    </header>

    <div id="msg-outter" class="mui-content">
        <div id="msg">


            <!-- 
				<div class="me_lists">
					<div class="header_img">
						<img src="../plugin/v3.1.6/images/picture.jpg" width="40px" height="40px" />
					</div>
					<div class="msg-wrapper left">
						<p class="msg-right-green">ss</p>
					</div>
				</div>
				<div class="friend_lists">
					<div class="header_img">
						<img src="../images/face-cat.jpg" width="40px" height="40px" />
					</div>
					<div class="msg-wrapper right">
						<p class="msg-left-white mui-content-padded">
							<img src="../css/registLogin/avatar.jpg">
						</p>
					</div>
				</div> -->


        </div>
    </div>

    <footer id="footer-link">
        <div class="footer-center">
            <button id="utils-link" class="btn btn-primary" style="margin-bottom: 2px;">
					<span class="mui-icon mui-icon-plus"></span>
				</button>
            <textarea id="msg-text" type="text" class='input-text'></textarea>

        </div>

        <div class="footer-right">
            <!-- 表情包 -->
            <button id="emoji-link" type="button" style="margin-left: 2px;">
					<svg style="margin-top: 3px;" xmlns="http://www.w3.org/2000/svg" width="20" height="15" viewBox="0 0 24 24" fill="none"
					 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-smile">
						<circle cx="12" cy="12" r="10"></circle>
						<path d="M8 14s1.5 2 4 2 4-2 4-2">
						</path>
						<line x1="9" y1="9" x2="9.01" y2="9">
						</line>
						<line x1="15" y1="9" x2="15.01" y2="9">
						</line>
					</svg>
				</button>
            <!-- 发送 -->
            <button class="btn btn-primary" id="send">
					<svg style="margin-top: 5px;" xmlns="http://www.w3.org/2000/svg" width="20" height="13" viewBox="0 0 24 24" fill="none"
					 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-send">
						<line x1="22" y1="2" x2="11" y2="13"></line>
						<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
					</svg>
				</button>
        </div>
    </footer>
    <!-- 表情包内容 -->
    <div id="emoji">

    </div>
    <!-- 工具栏 -->
    <div id="utils">
        <div id="util-picture">
            <span class="mui-icon mui-icon-image"></span>
        </div>
        <div>
            <span class="mui-icon mui-icon-location"></span>
        </div>
    </div>

</body>
<script src="../js/mui.min.js"></script>
<script type="application/javascript" src="../js/app.js"></script>
<script src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
<script type="text/javascript">
    var friendUserId;
    var friendNickname;
    var friendFaceImage;
    //表情包数组
    var emojiArray = ['😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎',
        '😍', '😘', '😗', '😙', '☺', '🙂', '🤗', '🤔', '😐', '😶', '🙄', '😏', '😣', '😥', '😮', '😪', '😫', '😴', '😛',
        '😌', '😨', '😰', '😱', '😵', '😳', '😡', '💩', '🤐', '🤤', '🤑', '😲', '😖', '😸', '😼', '😻', '👀'
    ];


    //初始化表情包
    function emojiInit(obj) {
        var emojiHTML = '';
        for (var i = 0; i < emojiArray.length; i++) {
            var str = "<span>" + emojiArray[i] + "</span>";
            emojiHTML += str;
        }
        obj.innerHTML = emojiHTML;
    }

    //图片预览效果
    var images;
    var urls = [];

    function imagesPreview() {
        images.forEach(function(item) {
            urls.push(item.src);
        });
        mui('.mui-content-padded').on('tap', 'img', function() {
            var index = images.indexOf(this);
            plus.nativeUI.previewImage(urls, {
                current: index,
                indicator: 'number'
            });
        });
    }


    function initChatContent(msgs, me, friendFaceImage) {

        var friendFaceImage = friendFaceImage.substring(0, 4) === "http" ? friendFaceImage : app.imgServerUrl +
            friendFaceImage;
        var meFaceImage = me.faceImage.substring(0, 4) === "http" ? me.faceImage : app.imgServerUrl + me.faceImage;
        if (msgs.length > 0) {
            var ChatHtml = '';
            for (var i = 0; i < msgs.length; i++) {
                var str = ''
                if (msgs[i].flag === 1) {
                    //本人发的
                    if (msgs[i].type === 0) {
                        //文本
                        str = `
								<div class="me_lists">
									<div class="header_img">
										<img src="` + meFaceImage +
                            `" width="40px" height="40px" />
									</div>
									<div class="msg-wrapper left">
										<p class="msg-right-green">` +
                            msgs[i].msg + `</p>
									</div>
								</div>							
							`;
                    }


                    if (msgs[i].type === 1) {
                        //图片
                        str = `
						<div class="me_lists">
							<div class="header_img">
								<img src="` + meFaceImage +
                            `" width="40px" height="40px" />
							</div>
							<div class="msg-wrapper left">
								<p class="msg-right-green mui-content-padded">
									<img src="` +
                            app.imgServerUrl +
                            msgs[i].msg + `">
								</p>
							</div>
						</div>		
					`;
                    }
                }



                if (msgs[i].flag === 2) {
                    //别人发的
                    if (msgs[i].type === 0) {
                        //文本
                        str = `
									<div class="friend_lists">
										<div class="header_img">
											<img src="` +
                            friendFaceImage +
                            `" width="40px" height="40px" />
										</div>
										<div class="msg-wrapper right">
											<p class="msg-left-white">` +
                            msgs[i].msg + `</p>
										</div>
									</div>
								
								`;
                    }


                    if (msgs[i].type === 1) {
                        //图片
                        str = `
							<div class="friend_lists">
								<div class="header_img">
									<img src="` +
                            friendFaceImage +
                            `" width="40px" height="40px" />
								</div>
								<div class="msg-wrapper right">
									<p class="msg-left-white mui-content-padded">
										<img src="` +
                            app.imgServerUrl + msgs[i].msg + `">
									</p>
								</div>
							</div>		
						`;
                    }


                }

                ChatHtml += str;

            }

            document.getElementById('msg').innerHTML = ChatHtml;

        }

    }


    mui.plusReady(function() {
        //获取我自己的用户信息
        var me = app.getUserGlobalInfo();
        //获取聊天页面的webview
        var chattingWebview = plus.webview.currentWebview();

        //获取上一个页面传入的好友属性值
        friendUserId = chattingWebview.friendUserId;
        friendNickname = chattingWebview.friendNickname;
        friendFaceImage = chattingWebview.friendFaceImage;

        //进去初始化聊天内容
        var ChatHistory = app.getUserChatHistory(me.id, friendUserId);
        //加载初始化聊天内容
        initChatContent(ChatHistory, me, friendFaceImage);
        //设置聊天页面的软键盘样式
        chattingWebview.setStyle({
            softinputMode: "adjustResize"
        });


        setTimeout(function() {
            images = [].slice.call(document.querySelectorAll('.mui-content-padded img'));
            //图片预览加载
            imagesPreview();
            resizeScreen();
        }, 250)

        //设置聊天页面的标题栏好友昵称
        document.getElementById("chatting-nickname").innerHTML = friendNickname;

        //footer对象
        var footer = document.getElementById('footer-link');
        //表情包内容对象
        var emojiContent = document.getElementById('emoji');
        //工具栏内容对象
        var utilsContent = document.getElementById('utils');

        //获取聊天列表容器对象
        var areaMsgList = document.getElementById("msg");
        //设置聊天记录进入页面的时候自动滚动到最后一条
        areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;

        //获取聊天发送内容文本框对象
        var msg_text = document.getElementById("msg-text");

        //获取发送消息按钮对象
        var send = document.getElementById("send");

        emojiInit(emojiContent);

        //把表情追加到输入栏
        emojiContent.addEventListener('click', function(e) {
            var str = e.target.innerText;
            if (str.length == 2) {
                send.style.backgroundColor = "#0062E1";
                msg_text.value += str;
            }
        })


        //是否打开表情栏标志
        var emojiFlag = 1;
        //是否打开工具栏标志
        var utilsFlag = 1;


        //上拉刷新
        areaMsgList.addEventListener('scroll', function() {
            if (areaMsgList.scrollTop == 0) {
                plus.nativeUI.showWaiting('刷新中');
                setTimeout(function() {
                    var msgH =
                        `
							<div class="me_lists">
								<div class="header_img">
									<img src="../plugin/v3.1.6/images/picture.jpg" width="40px" height="40px" />
								</div>
								<div class="msg-wrapper left">
									<p class="msg-right-green">测试</p>
								</div>
							</div>
						
						`;
                    areaMsgList.insertAdjacentHTML('afterBegin', msgH);
                    plus.nativeUI.closeWaiting();
                }, 1500);
            }

        })


        //打开表情包列表
        document.getElementById('emoji-link').addEventListener('click', function() {
            //打开或者关闭的时候默认取消输入框的焦点 防止呼出键盘
            msg_text.blur();
            if (emojiFlag == 1) {
                if (utilsFlag == 0) {
                    utilsContent.style.bottom = '-150px';
                    utilsFlag = 1;
                }
                areaMsgList.style.position = 'absolute';
                areaMsgList.style.bottom = '200px';
                footer.style.marginBottom = '150px';
                emojiContent.style.bottom = '0px';
                emojiFlag = 0;
            } else {
                footer.style.marginBottom = '0px';
                emojiContent.style.bottom = '-150px';
                areaMsgList.style.position = '';
                areaMsgList.style.bottom = '0px';
                areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
                emojiFlag = 1;
            }
        })

        msg_text.addEventListener('focus', function() {
            footer.style.marginBottom = '0px';
            emojiContent.style.bottom = '-150px';
            areaMsgList.style.position = '';
            areaMsgList.style.bottom = '0px';
            utilsContent.style.bottom = '-150px';
            areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
            emojiFlag = 1;
            utilsFlag = 1;

        })

        function closeAlls() {
            footer.style.marginBottom = '0px';
            emojiContent.style.bottom = '-150px';
            areaMsgList.style.position = '';
            areaMsgList.style.bottom = '0px';
            utilsContent.style.bottom = '-150px';
            emojiFlag = 1;
            utilsFlag = 1;
            resizeScreen();
        }

        //打开工具列表
        document.getElementById('utils-link').addEventListener('click', function() {
            //打开或者关闭的时候默认取消输入框的焦点 防止呼出键盘
            msg_text.blur();
            if (utilsFlag == 1) {
                if (emojiFlag == 0) {
                    emojiContent.style.bottom = '-150px';
                    emojiFlag = 1;
                }
                areaMsgList.style.position = 'absolute';
                areaMsgList.style.bottom = '200px';
                footer.style.marginBottom = '150px';
                utilsContent.style.bottom = '0px';
                utilsFlag = 0;
            } else {
                footer.style.marginBottom = '0px';
                utilsContent.style.bottom = '-150px';
                areaMsgList.style.position = '';
                areaMsgList.style.bottom = '0px';
                areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
                utilsFlag = 1;
            }
        })

        //监听用户输入，通过有无输入内容控制按钮的颜色
        msg_text.addEventListener("input", function() {
            //获取聊天发送内容
            var msg_text_content = msg_text.value;
            if (msg_text_content.length > 0) {
                send.style.backgroundColor = "#0062E1";
            } else {
                send.style.backgroundColor = "#fff";
                closeAlls();
            }
        });

        //当软键盘弹出后，我们的聊天窗口会从原来的全屏调整为半屏，对当前的窗口监听resize事件
        window.addEventListener("resize", function() {
            //调整屏幕宽度
            resizeScreen();
            document.getElementById("msg-outter").style.paddingBottom = "50px";
        });

        //发送消息按钮事件绑定
        send.addEventListener('tap', function() {
            /**
             * 发送消息之前检查网络状态
             */
            //获取网络状态
            var connectionStatus = plus.networkinfo.getCurrentType();
            if (connectionStatus == 1 || connectionStatus == 0) {
                app.showToast("请打开网络连接......", "error");
                return;
            }
            //获取消息文本框的内容
            var msg_text_content = msg_text.value;
            if (msg_text_content.length == 0) {
                return;
            }

            console.log('输出:' + msg_text_content);
            sendMsg(app.imgServerUrl + me.faceImage, {
                content: msg_text_content,
                type: 0
            });
            send.style.backgroundColor = "#fff";
            closeAlls();
            msg_text.value = '';
            //构建聊天
            var chatMsg = new app.ChatMsg(me.id, friendUserId, null, msg_text_content, 0);
            //构建DataContent
            var dataContent = new app.DataContent(app.CHAT, chatMsg, null);
            var wsWebView = plus.webview.getWebviewById('wh-chatlist.html');
            wsWebView.evalJS("CHAT.chat('" + JSON.stringify(dataContent) + "')");
            //保存聊天记录
            app.saveUserChatHistory(me.id, friendUserId, msg_text_content, 1, 0);

            //保存快照
            app.saveUserChatSnapshot(me.id, friendUserId, msg_text_content, true, 0);

        })

        //发送图片
        layui.use('upload', function() {
            var user = app.getUserGlobalInfo();
            var upload = layui.upload;
            //执行实例
            var uploadInst = upload.render({
                elem: '#util-picture', //绑定元素
                url: app.serverUrl + '/file/uploadImage', //上传接口
                method: 'post', //HTTP请求类型
                done: function(res) {
                    console.log(JSON.stringify(res));
                    if (res.status == 200) {
                        //构建聊天
                        var chatMsg = new app.ChatMsg(me.id, friendUserId, null, res.data, 1);
                        //构建DataContent
                        var dataContent = new app.DataContent(app.CHAT, chatMsg, null);
                        var wsWebView = plus.webview.getWebviewById('wh-chatlist.html');
                        //保存聊天记录
                        app.saveUserChatHistory(me.id, friendUserId, res.data, 1, 1);
                        //保存快照
                        app.saveUserChatSnapshot(me.id, friendUserId, res.data, true, 1);
                        wsWebView.evalJS("CHAT.chat('" + JSON.stringify(dataContent) + "')");
                        sendMsg(app.imgServerUrl + me.faceImage, {
                            content: res.data,
                            type: 1
                        });
                        closeAlls();
                    } else {
                        app.showToast(res.msg, "error");
                    }
                    layer.closeAll('loading');
                    //上传完毕回调
                },
                error: function() {
                    layer.msg(data.msg);
                    layer.closeAll('loading');
                    //请求异常回调
                }
            });
        });

    });



    //重新调整聊天窗口
    function resizeScreen() {
        //获取聊天列表容器对象
        var areaMsgList = document.getElementById("msg");
        //设置聊天记录进入页面的时候自动滚动到最后一条
        areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
    }


    //发送消息的函数
    function sendMsg(faceImg, msg) {
        var msgHtml = '';
        var msg_list = document.getElementById('msg');
        if (msg.type === 0) {
            //0代表文字类型
            msgHtml = `
					<div class="me_lists">
						<div class="header_img">
							<img src="` + faceImg +
                `" width="40px" height="40px"/>
						</div>
						<div class="msg-wrapper left">
							<p class="msg-right-green">` +
                msg.content + `</p>
						</div>
					</div>
				`;
            msg_list.insertAdjacentHTML('beforeend', msgHtml);
        } else if (msg.type === 1) {
            //1代表图片类型
            msgHtml = `
				<div class="me_lists">
					<div class="header_img">
						<img src="` + faceImg +
                `" width="40px" height="40px" />
					</div>
					<div class="msg-wrapper left">
						<p class="msg-right-green mui-content-padded">
							<img src="` +
                app.imgServerUrl + msg.content + `">
						</p>
					</div>
				</div>		
			`;
            msg_list.insertAdjacentHTML('beforeend', msgHtml);
            //预览图片重新加载
            images = [].slice.call(document.querySelectorAll('.mui-content-padded img'));
            //清空图片数组的url
            urls = [];
            imagesPreview();
        }
        //重新定位
        setTimeout(function() {
                resizeScreen();
            }, 250)
            //音乐播放
        playSendMsgSound();
    }


    //接受消息函数
    function receiveMsg(content, type) {
        var msgHtml = '';
        var msg_list = document.getElementById('msg');

        if (type == 0) {
            msgHtml = `
					<div class="friend_lists">
						<div class="header_img">
							<img src="` + app.imgServerUrl +
                friendFaceImage +
                `" width="40px" height="40px" />
						</div>
						<div class="msg-wrapper right">
							<p class="msg-left-white">` +
                content + `</p>
						</div>
					</div>		
					
				`;
            msg_list.insertAdjacentHTML('beforeend', msgHtml);
        } else if (type == 1) {
            msgHtml = `
						<div class="friend_lists">
							<div class="header_img">
								<img src="` + app.imgServerUrl +
                friendFaceImage +
                `" width="40px" height="40px" />
							</div>
							<div class="msg-wrapper right ">
								<p class="msg-left-white mui-content-padded">
									<img src="` +
                app.imgServerUrl + content + `">
								</p>
							</div>
						</div>		
					`;
            msg_list.insertAdjacentHTML('beforeend', msgHtml);
            //预览图片重新加载
            images = [].slice.call(document.querySelectorAll('.mui-content-padded img'));
            //清空图片数组的url
            urls = [];
            imagesPreview();
        }
        var msgTop = msg_list.scrollTop;
        if (msgTop > (msg_list.scrollHeight - msg_list.offsetHeight) / 2) {
            //重新定位
            setTimeout(function() {
                resizeScreen();
            }, 250)
        }

        playReceiveMsgSound();
    }

    //播放发送消息的铃声
    function playSendMsgSound() {
        //获取音频播放对象
        var audioPlayer = plus.audio.createPlayer("../mp3/send.mp3");
        audioPlayer.play();
    }

    //播放消息接受的铃声
    function playReceiveMsgSound() {
        //获取音频播放对象
        var audioPlayer = plus.audio.createPlayer("../mp3/msn.mp3");
        audioPlayer.play();
    }
</script>

</html>